package com.jt.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.google.gson.Gson;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 金帮嘉诚 @date 2021-08-25 星期三 14:37
 */

@Configuration
public class GatewayConfig {

    public GatewayConfig() {
        GatewayCallbackManager.setBlockHandler(
                new BlockRequestHandler() {
                    @Override //Mono 只有0个或1个元素的序列
                    public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {

                        Map<String, Object> map = new HashMap<>();
                        map.put("state", 429);
                        map.put("message", "two many request");

                        //alibaba的fastjson 将对象转化为json 但是有一些bug
//                        String jsonStr= JSON.toJSONString(map);
                        //Google公司gson 转化为json
                        Gson gson = new Gson();
                        String jsonStr = gson.toJson(map);


                        return ServerResponse.ok().body(Mono.just(jsonStr),
                                String.class);//响应数据的类型
                    }//WebFlux
                }
        );
    }
}

